package com.hundsun.cprs.yyt.web.action.classify;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.fileUpload.FileUploadUtil;
import com.hundsun.cprs.yyt.common.redis.BaseRedisDao;
import com.hundsun.cprs.yyt.service.classify.domain.Classify;
import com.hundsun.cprs.yyt.service.classify.domain.ClassifyTypeJson;
import com.hundsun.cprs.yyt.service.classify.enums.ClassifyIsDeletedYOrNEnum;
import com.hundsun.cprs.yyt.service.classify.enums.ClassifyTypeEnum;
import com.hundsun.cprs.yyt.service.classify.service.ClassifyService;
import com.hundsun.cprs.yyt.service.goods.domain.Goods;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.util.StringUtil;
import com.hundsun.cprs.yyt.util.UploadUtil;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.network.eclp.ex.common.PermissionEnum;
import com.hundsun.network.eclp.ex.security.AdminAccess;


@Controller
public class ClassifyAction extends  BaseAction{
	
	protected final Log logger = LogFactory.getLog(this.getClass());
	
	@Autowired
	private ClassifyService classifyService;
	@Autowired
	private GoodsService goodsService;
	
	@Resource(name = "imageUploadUtil")
	private FileUploadUtil fileUploadUtil;
	/**
	 * 通用数据初始化
	 */
	public void addReferenceData(ModelMap model){
		//查询下一个类目的id
		//model.put("plateId", classifyService.selectClassifyIdOfNext());
		model.put("classifyTypeMap", ClassifyTypeEnum.toMap());
		model.put("classifyOneList", classifyService.selectOneClassify(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
	}
	
	/**
	 * 通用数据初始化
	 */
	public MultipartHttpServletRequest referenceData(HttpServletResponse response,HttpServletRequest request)throws Exception{
		response.setContentType("text/html;charset=utf-8;");
		request.setCharacterEncoding("utf-8");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		return multipartRequest;
	}
	
	/**
	 * 类目录树的展示
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND)
	@RequestMapping(value = "/classify/list")
	public String classifyListTree(ModelMap model) throws Exception {
		return "/classify/classifyIndex";
	}
	
	/**
	 * 类目录树的展示(将所有的启用的类目录，包括一级、二级)
	 * @return
	 */
	 @RequestMapping(value = "/ajax/getclassifyTypeTree")
	 public @ResponseBody List<ClassifyTypeJson> getProjectTypeTree() {
		 return classifyService.getClassifyTree();
	 }
	 
	 /**
	  * 左边是类目录树形展示
	  * @return
	  */
	@RequestMapping(value = "/classify/classifyLeft")
	public String classifyLeftTree() throws Exception {
		return "/classify/classifyLeft";
	}

	 /**
	  * 右边是可以进行操作的界面
	  * @return
	  */
	@RequestMapping(value = "/classify/classifyRight")
	public String classifyRightTree() throws Exception {
		return "/classify/classifyRight";
	}
	
	/**
	 * 跳转到添加类目页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/ajax/unique/classifyCode.json")
	public @ResponseBody JSONObject projectClssifyAddByGet(@RequestParam("classifyCode") String classifyCode,ModelMap model) throws Exception {
		
		JSONObject result = new JSONObject();
		
		if(classifyCode == null){
			model.put("message", "类目编码值不能为空！");
		}
		try {
			Classify  classify = classifyService.selectClassifyByCode(classifyCode);
			if(classify != null){
				result.put("message", "类目编码不能重复！");
			}
		} catch (Exception e) {
			log.error("通过类目编码查询类目异常！",e);
			result.put("message", "查询类目编码异常！");
		}
		return result;
	}
	
	/**
	 * 跳转到添加类目页面
	 * 
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_ADD)
	@RequestMapping(value = "/classify/add", method = RequestMethod.GET)
	public String projectClssifyAddByGet(@ModelAttribute("classify")Classify classify,HttpServletRequest request,
			                            ModelMap model,HttpSession session) throws Exception {
		
		this.addReferenceData(model);
		return "/classify/classifyAdd";
	}
	
	/**
	 * 添加类目信息
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_ADD)
	@RequestMapping(value = "/classify/add", method = RequestMethod.POST)
	@ResponseBody
	public JsonModel projectClssifyAddByPost(@RequestBody Map<String,String> requestMap, HttpServletRequest request) throws Exception {
		try {
			Classify classify = JSON.parseObject(JSON.toJSONString(requestMap), Classify.class);
			this.validateParam(classify, request);
			if(classify.getType().compareTo(ClassifyTypeEnum.ONE_CLASSIFY_TYPE.getCode()) == 0){
				classify.setParentId(ClassifyTypeEnum.ONE_CLASSIFY_TYPE.getCode());
			}
			this.classifyService.createClassify(classify);
			return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"分类新增成功");
		} catch (Exception e) {
			log.error("分类新增异常:",e);
			return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
		}
	}

	
	/**
	 * 更新类目录信息
	 * @return
	 */
	@RequestMapping(value = "/classify/calssifyView", method = RequestMethod.GET)
	public String projectClssifyView(ModelMap model, @RequestParam("id") int classifyId) throws Exception {
		
		 try {
			//根据id获取类目信息
			model.put("classify",classifyService.selectClassifyById(classifyId));
			//所有的一级目录显示
			model.put("classifyOneList", classifyService.selectOneClassify(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
		 } catch (ServiceCodeException e) {
			 logger.error("根据id查询类目信息失败！",e);
			 model.put("message", "查询类目信息异常！");
		 } catch (Exception e) {
			  logger.error("根据id查询类目信息失败！", e);
			  model.put("message", "查询类目信息异常！");
		 }
		return "/classify/classifyView";
	}
	
	/**
	 * 更新类目录信息
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_UPDATE)
	@RequestMapping(value = "/classify/update", method = RequestMethod.GET)
	public String projectClssifyUpdate(ModelMap model, @RequestParam("id") int classifyId) throws Exception {
		
		 try {
			//根据id获取类目信息
			model.put("classify",classifyService.selectClassifyById(classifyId));
			//所有的一级目录显示
			model.put("classifyOneList", classifyService.selectOneClassify(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
		 } catch (ServiceCodeException e) {
			 logger.error("根据id查询类目信息失败！",e);
			 model.put("message", "查询类目信息异常！");
		 } catch (Exception e) {
			  logger.error("根据id查询类目信息失败！", e);
			  model.put("message", "查询类目信息异常！");
		 }
		return "/classify/classifyUpdate";
	}
	
	/**
	 * 更新类目录信息
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_UPDATE)
	@RequestMapping(value = "/classify/update", method = RequestMethod.POST)
	@ResponseBody
	public JsonModel projectClssifyUpdate(@RequestBody Map<String,String> requestMap,HttpServletRequest request) throws Exception {
		try{
			Classify classify = JSON.parseObject(JSON.toJSONString(requestMap), Classify.class);
			//更新类目信息
			classifyService.updateClassify(classify);
			return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"分类修改成功");
		}catch (Exception e){
			return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
		}
	}
	
	/**
	 * 显示类目录，一级目录禁用，二级目录无法启用
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_ENABLE)
	@RequestMapping(value = "/classify/enable",method = RequestMethod.POST)
	public @ResponseBody String classifyEnable(ModelMap model, @RequestParam("id") int id) throws Exception {
		
		//JSONObject result = new JSONObject();
		String message = "";
		Classify classify = classifyService.selectClassifyById(id);
		if(classify == null){
			message = "查询类目录异常，无法进行启用！";
			//result.put("message", "查询类目录异常，无法进行启用！");
			return message;
		}
		
		//是要启动一级目录，可直接启动
		if(classify.getParentId() == ClassifyTypeEnum.ONE_CLASSIFY_TYPE.getCode()){
			//一级目录是禁用状态
			if(classify.getIsDeleted().equals(ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode())){
				//result.put("message",  ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode());
				message = ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode();
				return message;
			}else{     
				message = "类目录已经是启用状态！";
				//result.put("message","类目录已经是启用状态！");
				return message;
			}
		}
		
		//如果查询到的parentId不为0，则是在启用二级目录
		if(classify.getParentId() != ClassifyTypeEnum.ONE_CLASSIFY_TYPE.getCode() && classify.getIsDeleted().equals(ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode())){
			//查询二级分类对应的一级分类信息
			Classify classifyParent = classifyService.selectClassifyById(classify.getParentId());
			if(classifyParent == null){
				message = "此二级类目录没有所属一级类目，不允许启用！";
				//result.put("message", "此二级类目录没有所属一级类目，不允许启用！");
				return message;
			}
			
			if(classifyParent.getIsDeleted().equals(ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode())){
				message = "父目类型状态为禁用，不允许启用！";
				//result.put("message", "父目类型状态为禁用，不允许启用！");
				return message;
			}
			
			message = ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode();
			//result.put("message",  ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode());
		}else{
			message = "类目录已经是启用状态！";
			//result.put("message", "类目录已经是启用状态！");
		}
		return message;
	}
	
	/**
	 * 启用类目录，一级目录禁用，二级目录无法启用
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_ENABLE)
	@RequestMapping(value = "/classify/enable",method = RequestMethod.GET)
	public String updateClassifyEnable(ModelMap model, @RequestParam("id") int id) throws Exception {
		try {
			Classify classify = new Classify();
			classify.setId(id);
			classify.setIsDeleted(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode());
			//启用二级目录
			classifyService.updateOneClassifyAndTwoClassify(classify);
		} catch (Exception e) {
			log.error(e);
			model.put("message", "启用类目录异常，请重试！");
		}
		return "/classify/classifyHelp";
	}

	/**
	 * 禁用类目录(禁用一级目录，二级目录也会禁用)
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_DISABLE)
	@RequestMapping(value = "/classify/close")
	public String classifyClose(ModelMap model,@RequestParam("id") int id) throws Exception {
		try {
			Classify classify = new Classify();
			classify.setId(id);
			classify.setIsDeleted(ClassifyIsDeletedYOrNEnum.Y_CLASSIFY_TYPE.getCode());
			//根据id删除类目录
			classifyService.updateOneClassifyAndTwoClassify(classify);
		} catch (Exception e) {
			log.error(e);
			model.put("message", "删除类目录异常，请重试！");
		}
		return "/classify/classifyHelp";
	}
	
	
	/**
	 * 删除类目录(删除一级目录，二级目录也会删除)
	 * @return
	 */
	@AdminAccess(PermissionEnum.CLASSIFY_MANAGE_DEFEND_DELETE)
	@RequestMapping(value = "/classify/delete")
	public String classifyDelete(ModelMap model,@RequestParam("id") int id) throws Exception {
		try {
			List<Classify>  classifyList = new ArrayList<>();
			//如果用户要删除一级目录，则要检查旗下所有二级目录下是否有商品存在
			List<Classify>  twoClassifys = classifyService.selectTwoClassifyByParentId(id, null);
			
			if(twoClassifys == null || twoClassifys.size() <= 0){
				Classify classify = classifyService.selectClassifyById(id);
				if(classify !=null){
					classifyList.add(classify);
				}
			}else{
				classifyList.addAll(twoClassifys);
			}

			for(Classify twoclassify : classifyList){
				GoodsQuery goodsQuery = new GoodsQuery();
				goodsQuery.setClassifyId(twoclassify.getId());
				goodsService.queryGoodsByPage(goodsQuery);
				List<GoodsInfo>  goods = goodsQuery.getData();
				if(goods!=null && goods.size() > 0){
			    	model.put("message", "分类下存在商品，无法删除类目录信息！");
			    	return "/classify/classifyHelp";
			   }
			}
		
			Classify classify = new Classify();
			classify.setId(id);
			//根据id删除类目录
			classifyService.deleteClassifyById(id);
			
		} catch (Exception e) {
			log.error(e);
			model.put("message", "删除类目录异常，请重试！");
		}
		return "/classify/classifyHelp";
	}
	
	/**
	 * 修改参数验证
	 * @param classify
	 */
	private void validateParam(Classify classify,HttpServletRequest request) {
		if(request.getMethod().equals(RequestMethod.POST.toString())) {
			if (StringUtils.isBlank(classify.getCode())) {
				throw new ServiceCodeException(EnumBusinessCode.CLASSIFY_1601.getErrorNo(),
						EnumBusinessCode.CLASSIFY_1601.getErrorInfo()+"，请重新输入！");
			}
			if (!StringUtil.regexLetterNum(classify.getCode())) {
				throw new ServiceCodeException(EnumBusinessCode.CLASSIFY_1602.getErrorNo(), 
						EnumBusinessCode.CLASSIFY_1602.getErrorInfo()+"，请重新输入！");
			}
			if (StringUtils.isBlank(classify.getName())) {
				throw new ServiceCodeException(EnumBusinessCode.CLASSIFY_1603.getErrorNo(),
						EnumBusinessCode.CLASSIFY_1603.getErrorInfo()+"，请重新输入！");
			}
			
			if(StringUtils.isBlank(classify.getOriginalImageUrl())
					||StringUtils.isBlank(classify.getSmallImageUrl())
					||StringUtils.isBlank(classify.getBigImageUrl())) {

				throw new ServiceCodeException(EnumBusinessCode.CLASSIFY_1605.getErrorNo(),
						EnumBusinessCode.CLASSIFY_1605.getErrorInfo()+"，请上传图片!");
			}
		}
	}
}
